﻿using System;
using System.Collections;
using System.Collections.Generic;

using UnityEngine;

public enum NetState
{
    Null = 0,
    Succeed = 1,//请求成功
    Timeout = 2,//请求超时
    Mistake = 3,//请求错误
}

public class NetTimeBag
{
    public NetState _netState;
    public DateTime _dateTime;
}

namespace Util
{
    public class TimeNet : MonoBehaviour
    {
        private static TimeNet _ins;

        public static TimeNet ins
        {
            get
            {
                if (_ins == null)
                {
                    var t = Timer.Instance;
                    GameObject obj = Timer.TimeObj;
                    _ins = obj.AddComponent<TimeNet>();
                }
                return _ins;
            }
        }

        public System.Action doneSaveTime;

        //private string url = "http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=";            //免费获取北京时间的Web接口
        private string url = "http://www.metoocom.com:7079/GetTime.ashx";

        private int RangNum;

        private void Start()
        {
        }

        //private static bool isOnNetTime = true;

        private static bool inRequest = true;
        private static List<Action<NetTimeBag>> RequestList = new List<Action<NetTimeBag>>();

        private int TimeoutNum = 0;//最大超时次数
        private int TimeoutMaxNum = 3;//最大超时次数

        private float m_Timeout = 2;//超时时间

        private NetTimeBag m_NetTimeBag = new NetTimeBag();

        private Timer.TimerProc tp;

        //请求时间
        public void Request()
        {
            if (inRequest)//不在请求中
            {
                inRequest = false;
                TimeoutMonitor();
                //RangNum = UnityEngine.Random.Range(1, 999);
                //url = url + RangNum.ToString();
                StartCoroutine(OnRequest());
            }
        }

        private void TimeoutMonitor()//超时监听
        {
            Timer.Instance.Remove(tp);
            tp = Timer.Instance.Add(m_Timeout, 1, () =>
               {
                   m_NetTimeBag._netState = NetState.Timeout;
                   m_NetTimeBag._dateTime = DateTime.Now;

                   StopCoroutine(OnRequest());
                   ComeBack();
               });
        }

        private IEnumerator OnRequest()
        {
            WWW www = new WWW(url);
            yield return www;                   //在这里阻塞,等待响应之后返回
            NetState state = NetState.Null;
            DateTime data = DateTime.Now;
            if (!string.IsNullOrEmpty(www.error))
            {
                state = NetState.Mistake;
            }
            else if (www.isDone)
            {
                state = NetState.Succeed;
                //string timeStamp = www.text.Split('=')[1].Substring(0, 10);  //网页获取的数据长度超了，所以要裁剪
                data = Analysis(www.text);
            }
            m_NetTimeBag._netState = state;
            m_NetTimeBag._dateTime = data;
            ComeBack();
        }

        private void ComeBack()//回来的数据
        {
            if (inRequest)//如果超时则不再处理回来的数据
            {
                return;
            }
            Timer.Instance.Remove(tp);
            inRequest = true;
            if (m_NetTimeBag._netState == NetState.Timeout)
            {
                if (TimeoutNum <= TimeoutMaxNum)
                {
                    TimeoutNum++;
                    Request();
                }
                else
                {
                    TimeoutNum = 0;
                    DisposeComeBackData();
                }
            }
            else
            {
                TimeoutNum = 0;
                DisposeComeBackData();
            }
        }

        //处理回来的数据
        private void DisposeComeBackData()
        {
            for (int i = 0; i < RequestList.Count; i++)
            {
                if (RequestList[i] != null)
                {
                    RequestList[i].Invoke(m_NetTimeBag);
                }
            }
            RequestList.Clear();
        }

        /// <summary>
        /// 获取网络时间
        /// </summary>
        /// <param name="CallBack"></param>
        public void NetTime(Action<NetTimeBag> CallBack)
        {
            if (!RequestList.Contains(CallBack))
            {
                RequestList.Add(CallBack);
            }
            Request();
        }

        /// <summary>
        /// 解析时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public DateTime Analysis(string time)
        {
            DateTime newStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long newTime = long.Parse(time + "0000000");
            TimeSpan toNew = new TimeSpan(newTime);
            return newStart.Add(toNew);
        }

        #region
        /*
        public void GetTimeData()
        {
            //RangNum = UnityEngine.Random.Range(1, 999);
            //url = url + RangNum.ToString();
            StartCoroutine(GetTime());
        }

        private IEnumerator GetTime()
        {
            WWW www = new WWW(url);
            yield return www;                   //在这里阻塞,等待响应之后返回
            if (www.isDone && string.IsNullOrEmpty(www.error))
            {
                Compare(www);
            }
        }

        public void Compare(WWW www)
        {
            //string timeStamp = www.text.Split('=')[1].Substring(0, 10);  //网页获取的数据长度超了，所以要裁剪
            SaveManager.Instance.SaveCurTime(www.text);
            if (doneSaveTime != null)
            {
                doneSaveTime.Invoke();
            }
        }

        public void SaveStartTime(int missionID)
        {
            //RangNum = UnityEngine.Random.Range(1, 999);
            //url = url + RangNum.ToString();
            StartCoroutine(GetCurTime(missionID));
        }

        private IEnumerator GetCurTime(int missionID)
        {
            WWW www = new WWW(url);
            yield return www;                   //在这里阻塞,等待响应之后返回
            if (www.isDone && string.IsNullOrEmpty(www.error))
            {
                DoSave(www, missionID);
            }
        }

        public void DoSave(WWW www, int missionID)
        {
            //string timeStamp = www.text.Split('=')[1].Substring(0, 10);  //网页获取的数据长度超了，所以要裁剪
            SaveGame.Save(string.Format("StartTime{0}", missionID.ToString()), www.text);
            Compare(www);
        }

        /// <summary>
        /// 解析时间
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public DateTime Analysis(string time)
        {
            DateTime newStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long newTime = long.Parse(time + "0000000");
            TimeSpan toNew = new TimeSpan(newTime);
            return newStart.Add(toNew);
        }
        */
        #endregion
    }
}